<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="type == 1 ? '添加知识' : type == 2 ? '编辑知识' : '知识详情'"
      :visible="open"
      width="1000px"
      append-to-body
      @close="cancel()"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="type == 1 || type == 2 ? rules : {}"
        label-width="80px"
      >
        <!-- 知识类目 下拉框 -->
        <el-form-item label="知识类目" prop="categoryId">
          <el-select
            v-if="(type == 1 || type == 2) && !categoryid"
            v-model="form.categoryId"
            placeholder="请选择知识类目"
            filterable
            clearable
          >
            <el-option
              v-for="item in categorylist"
              :label="item.categoryName"
              :key="item.categoryId"
              :value="item.categoryId"
            >
              {{ item.categoryName }}
            </el-option>
          </el-select>
          <div v-else>
            <div
              v-for="item in categorylist"
              :key="item.categoryId"
              v-if="item.categoryId == form.categoryId"
            >
              {{ item.categoryName }}
            </div>
          </div>
        </el-form-item>

        <el-form-item label="知识标题" prop="title">
          <el-input
            v-if="type == 1 || type == 2"
            v-input-restrict
            v-model="form.title"
            maxlength="40"
            show-word-limit
            placeholder="请输入知识标题"
          />
          <div v-else>{{ form.title }}</div>
        </el-form-item>
        <el-form-item label="封面" prop="knowledgePic">
          <div class="uploadCourseCover" v-if="type == 1 || type == 2">
            <!-- 上传图片 -->
            <div
              v-if="form.knowledgePic"
              class="upload-head"
              @click="editCropper()"
            >
              <img v-bind:src="form.knowledgePic" class="cover" />
            </div>
            <div v-else class="upload-head" @click="editCropper()">
              <div>
                <img src="@/assets/images/add.png" class="add" alt="" />
              </div>
              <div>上传图片</div>
            </div>

            <div class="uploadTipbottom">
              建议图片比例16:9，支持jpg、png格式，图片小于5M
            </div>
          </div>
          <div class="uploadCourseCover" v-else>
            <div v-if="form.knowledgePic" class="upload-head">
              <img v-bind:src="form.knowledgePic" class="cover" />
            </div>
          </div>

          <vuecut
            :type="2"
            :uuid="form.dirName"
            :isKnowledge="true"
            :w="320"
            :h="180"
            url=""
            @coverResult="coverResult"
            title="图片上传"
            :open.sync="vuecutshow"
          ></vuecut>
        </el-form-item>

        <el-form-item label="知识内容" prop="content">
          <wangEditor
            v-if="type == 1 || type == 2"
            :uuid="form.dirName"
            v-model="form.content"
            :isKnowledge="true"
            @turnWord="uploadWordToNode($event, form)"
          />
          <div
            v-else
            v-html="form.content"
            style="overflow: auto; white-space: pre-wrap"
          ></div>
        </el-form-item>
        <el-form-item label="知识附件" prop="knowledgeFile">
          <input
            style="display: none"
            class="uploadContain_input"
            type="file"
            accept=".gif, .png, .jpeg,  .jpg,  .mp4, .webm, .pdf, .docx, .doc, .rtf, .pptx, .ppt,  .xls, .xlsx ,.wps ,.ofd
        ,.txt ,.js ,.json ,.css ,.sql ,.xml ,.java ,.cs(c#)"
            ref="fileInput"
            @change="uploadFile($event)"
            multiple
          />
          <div
            v-if="type == 1 || type == 2"
            class="addflie flex shou"
            style="background: #28b28b"
            @click="uploadType('上传知识附件')"
          >
            <img src="@/assets/images/courseadd/upload.png" alt="" />上传附件
          </div>
          <div
            @click="openfile(item1.url, item1.name)"
            class="file flex shou"
            v-for="(item1, index1) in form.knowledgeFile"
            :key="index1"
          >
            <img class="icon" src="@/assets/images/hxz.png" alt="" />
            <img class="iconactive" src="@/assets/images/lvhxz.png" alt="" />
            <div class="name overtxt">{{ item1.name }}</div>
            <img
              v-if="type == 1 || type == 2"
              @click.stop="delCourseware(index1)"
              class="del"
              src="@/assets/images/del.png"
              alt=""
            />
          </div>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: flex-end"
      >
        <el-button
          v-preventReClick
          v-if="type == 2 || type == 4"
          @click="cancel"
          >取 消</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm"
          v-if="type == 1 || type == 2"
          >保存并退出</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="submitForm('submit')"
          v-if="type == 1"
          >提交</el-button
        >
        <el-button
          v-preventReClick
          type="danger"
          @click="audit(2)"
          v-if="type == 4"
          >驳 回</el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="audit(1)"
          v-if="type == 4"
          >通 过</el-button
        >
        <el-button
          v-preventReClick
          @click="cancel"
          v-if="type == 3 || type == 5"
          >关 闭</el-button
        >
      </div>
    </el-dialog>
    <fileDrawer
      :show.sync="drawer"
      :url="drawerurl"
      :name="drawername"
      :type="drawertype"
      :isHttps="isHttps"
    ></fileDrawer>
  </div>
</template>
  
<script>
import fileDrawer from "@/components/fileDrawer.vue";
import { uploadOSS, fammterString } from "@/api/upload";
import { returnIcon } from "@/utils/util";
import wangEditor from "@/components/wangEditor.vue";
import { getCategoryList } from "@/api/knowledge/category";
import {
  postknowledgetemporary,
  putknowledgetemporary,
  getknowledgetemporary,
  getknowledge,
  submitknowledgetemporary,
} from "@/api/knowledge/knowledge";
export default {
  components: { wangEditor, fileDrawer },
  props: {
    open: Boolean,
    // type 4为审核 5为正式详情
    type: [Number, String],
    // 知识id用于 编辑审核查看
    id: [Number, String],
    // 用于添加时如果有 知识点分类id带入
    categoryid: [Number, String],
  },
  data() {
    return {
      // 文件组件弹框
      drawer: false,
      drawerurl: "",
      drawername: "",
      drawertype: 1,
      isHttps: false,
      returnIcon: function (url, type) {
        return returnIcon(url, type);
      },
      vuecutshow: false,
      categorylist: [],
      // 表单参数
      form: {
        knowledgeFile: [],
      },
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "知识类目不能为空", trigger: "blur" },
        ],
        title: [
          { required: true, message: "知识标题不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "知识内容不能为空", trigger: "blur" },
        ],
        knowledgePic: [
          { required: true, message: "知识图片", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    open(e) {
      if (e) {
        this.getCategorylist();

        if (this.type == 1) {
          this.reset();
          if (this.categoryid) {
            this.form.categoryId = this.categoryid;
          }
        }
        if (this.type == 2 || this.type == 3 || this.type == 4) {
          getknowledgetemporary(this.id).then((res) => {
            res.data.knowledgeFile = res.data.knowledgeFile
              ? JSON.parse(res.data.knowledgeFile)
              : [];
            this.form = res.data;
          });
        }
        if (this.type == 5) {
          getknowledge(this.id).then((res) => {
            res.data.knowledgeFile = res.data.knowledgeFile
              ? JSON.parse(res.data.knowledgeFile)
              : [];
            this.form = res.data;
          });
        }
      }
    },
  },
  mounted() {},
  methods: {
    delCourseware(index) {
      console.log(index);
      this.form.knowledgeFile.splice(index, 1);
      this.$forceUpdate();
    },
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();

        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };

        xhr.send();
      });
    },
    saveAs(blob, filename) {
      var link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },
    openfile(url, name) {
      // window.open(url, "_blank");
      this.getBlob(url).then((blob) => {
        this.saveAs(blob, name);
      });
      // let uploadType = url
      //   .slice(url.lastIndexOf("."), url.length)
      //   .toLowerCase();
      // let arr = [
      //   ".gif",
      //   ".png",
      //   ".jpeg",
      //   ".jpg",
      //   ".mp4",
      //   ".webm",
      //   ".pdf",
      //   ".wps",
      //   ".docx",
      //   ".doc",
      //   ".rtf",
      //   ".pptx",
      //   ".ppt",
      //   ".xls",
      //   ".xlsx",
      //   ".wps",
      //   ".ofd",
      //   ".txt",
      //   ".js",
      //   ".json",
      //   ".css",
      //   ".sql",
      //   ".xml",
      //   ".java",
      //   ".cs(c#)",
      // ];
      // if (arr.indexOf(uploadType) > -1) {
      //   this.drawer = true;
      //   this.drawerurl = url;
      //   this.drawername = name;
      //   this.drawertype = type;
      // } else {
      //   window.open(url, "_blank");
      // }
    },
    /* 按钮来判断上传类型 并记录 */
    uploadType(type) {
      this.$refs.fileInput.click();
    },
    async uploadFile(event) {
      let files = event.target.files;
      let formData = new FormData();
      for (let i = 0; i < Array.from(files).length; i++) {
        if (
          Array.from(files)[i].name.substring(
            Array.from(files)[i].name.lastIndexOf(".") + 1
          ) == "ppt"
        ) {
          this.$modal.msgWarning("不支持上传ppt文件格式");
          return false;
        } else {
          formData.append(
            "files",
            new File([Array.from(files)[i]], Array.from(files)[i].name)
          );
        }
      }

      let path = "";
      path = fammterString(2, this.form.dirName, "knowledge");
      let res = await uploadOSS(files, path, true, event);
      this.form.knowledgeFile = [...this.form.knowledgeFile, ...res];
      this.$forceUpdate();
      console.log(this.form.knowledgeFile, res);
      event.target.value = "";
      this.$modal.msgSuccess("上传成功");
    },
    /** 组件返回图片 */
    coverResult(e) {
      this.form.knowledgePic = e;
    },

    editCropper() {
      this.vuecutshow = true;
    },
    uploadWordToNode(formData, item) {
      item.content += formData;
    },
    /* 获取分类列表 并如果有的话获取 第一个分类获取详细*/
    async getCategorylist() {
      try {
        let res = await getCategoryList();
        if (res.code == 200) {
          this.categorylist = res.rows;
        }
      } finally {
      }
    },
    /* 审核按钮 1通过 2拒绝*/
    audit(status) {
      this.$emit("audit", { row: this.form, status: status });
      this.$emit("update:open", false);
    },
    /** 提交按钮 */
    submitForm: function (type) {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            let res;
            let params = JSON.parse(JSON.stringify(this.form));
            params.knowledgeFile = JSON.stringify(params.knowledgeFile);
            if (this.type == 1) {
              params.port = "pc";

              res = await postknowledgetemporary(params);
              if (type == "submit") {
                try {
                  let res2;
                  res2 = await submitknowledgetemporary(res.data.id, 1);
                  if (res2.code == 200) {
                    this.$modal.msgSuccess(
                      `添加成功，请前往【知识草稿】查看审核进度`
                    );
                    this.$emit("refresh");
                    this.$emit("update:open", false);
                  }
                } finally {
                }
              } else {
                if (res.code == 200) {
                  this.$message({
                    message:
                      this.type == 1
                        ? "添加成功，请前往【知识草稿】查看审核进度"
                        : "修改成功",
                    type: "success",
                  });
                  this.$emit("refresh");
                  this.$emit("update:open", false);
                }
              }
            } else {
              res = await putknowledgetemporary(params);
              if (res.code == 200) {
                this.$message({
                  message:
                    this.type == 1
                      ? "添加成功，请前往【知识草稿】查看审核进度"
                      : "修改成功",
                  type: "success",
                });
                this.$emit("refresh");
                this.$emit("update:open", false);
              }
            }
          } finally {
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        dirName: this.guid(),
        categoryId: undefined,
        title: undefined,
        content: undefined,
        knowledgePic: undefined,
        knowledgeFile: [],
      };
      this.resetForm("form");
    },
    cancel() {
      this.$emit("update:open", false);
    },
    guid() {
      let uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        }
      );
      return uuid;
    },
  },
};
</script>
  <style scoped lang="scss">
.addflies {
  margin-bottom: 20px;
}

// 文件列表
.file:hover {
  background: rgba(204, 204, 204, 0.4);

  .del {
    display: block;
  }

  .name {
    color: rgba(39, 196, 120, 1);
  }

  .icon {
    display: none;
  }

  .iconactive {
    display: block;
  }
}

.file {
  width: 275px;
  height: 20px;

  .icon {
    display: block;
    margin: auto 3px auto 3px;
    width: 11px;
    height: 14px;
  }

  .iconactive {
    display: none;
    margin: auto 3px auto 3px;
    width: 11px;
    height: 14px;
  }

  .name {
    width: 240px;
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
    color: rgba(48, 49, 51, 1);
  }

  .del {
    margin: auto 0 auto 0;
    display: none;
    width: 10px;
    height: 10px;
  }
}
.addflie {
  width: 135px;
  margin-bottom: 10px;

  img {
    margin: auto 8px auto 0;
    width: 14px;
    height: 14px;
  }

  padding: 0 12px;
  height: 32px;
  border-radius: 8px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  line-height: 32px;
}
// 上传封面样式
.uploadCourseCover {
  .uploadTip {
    line-height: 160px;
    height: 100px;
  }

  .upload-head {
    width: 162px;
    height: 102px;

    .add {
      width: 20px;
      height: 20px;
      margin: 25px auto 0 auto;
    }

    .cover {
      width: 160px;
      height: 100px;
    }
  }

  .upload-head:hover:after {
    line-height: 100px;
  }
}
</style>
  